package com.zhiyou100.review.day020.homework;

/**
 * @packageName: Homework01
 * @className: com.zhiyou100.review.day020.homework
 * @Description: TODO 三个同学给一个老师每人交5本作业  实现线程同步
 * @author: yang
 * @date: 7/1/20
 */
public class Homework01 {
    public static void main(String[] args) {
        Object o = new Object();
        // 创建锁对象
        HandInHomework handInHomework = new HandInHomework(o);
        new Thread(handInHomework, "小明").start();
        new Thread(handInHomework, "小花").start();
        new Thread(handInHomework, "小张").start();
        new Thread(handInHomework, "小杨").start();
        new Thread(handInHomework, "小芳").start();
    }
}

class HandInHomework implements Runnable {
    Object teacher;

    public HandInHomework(Object teacher) {
        this.teacher = teacher;
    }

    @Override
    public void run() {
        int max = 5;
        for (int i = 0; i < max; i++) {
            synchronized (teacher) {
                // 用 teacher 作为锁
                System.out.println(Thread.currentThread().getName() + " 给老师交第 " + (i + 1) + " 本作业！");
            }
            try {
                Thread.sleep(200);
                // 休眠一会
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
